package com.suwish.pc.adb;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

import com.suwish.device.util.Platform;
import com.suwish.pc.phone.PhoneManager;

/**
 * 
 * <code>AdbManager</code>设计之初的目的是使用ADB命令通过Process的方式与
 * android设备通信，因此，所有android设备产生的事件都有这个类向外通知。</p>
 * 
 * 但是考虑到ADB命令功能有限，无法完成对android设备的监控功能，并且命令行ADB
 * 
 * @author Min
 *
 */
public class AdbManager {

	
	public final static String ADB_PATH = Platform.getAppLibDir() + File.separator + "dist" 
						+ File.separator + "adb" + (Platform.isWindows() ?  ".exe" : "");
	public final static String AAPT_PATH = Platform.getAppLibDir() + File.separator + "dist" 
						+ File.separator + "aapt" + (Platform.isWindows() ?  ".exe" : "");
	
	
	public final static String ADB_DEVICES_LIST_TITLE = "List of devices attached";
	
	public AdbManager(PhoneManager manager){
		
	}
	/**
	 * 
	 * @deprecated
	 */
	public void startMonitor(){
		
	}
	/**
	 * 
	 * @deprecated
	 */
	public void stopMonitor(){
		
	}
	/**
	 * 使用给定的命令开启一个进程。
	 * 
	 * @param command
	 * @return
	 * @throws IOException
	 */
	public static Process execCommand(Command command) throws IOException{
		return execCommand(command, null);
	}
	/**
	 * 使用给定的命令开启一个进程。并添加一个收集错误信息的回调接口。</p>
	 * 
	 * 注意此回调接口针对于错误流按行返回字符串
	 * @param command
	 * @param callback
	 * @return
	 * @throws IOException
	 */
	public static Process execCommand(Command command, CmdCallback callback) throws IOException{
		Process process = Runtime.getRuntime().exec(command.parseCommand());
//		final BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
		processErrorStream(new BufferedReader(new InputStreamReader(process.getErrorStream())), callback);
		return process;
	}
	/**
	 * 执行给定的命令，并返回执行结果
	 * @param command
	 * @return
	 * @throws IOException
	 */
	public static String queryResult(Command command, boolean newLine) throws IOException{
		Process process = execCommand(command);
		BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
		StringBuilder builder = new StringBuilder();
		String buffer = null;
		while((buffer = reader.readLine()) != null){
			builder.append(buffer + (newLine ? Platform.getLineSeparator() : ""));
		}
		return builder.toString();
	}
	/**
	 * 
	 * 
	 * 
	 * @param reader
	 * @param callback
	 */
	public static void processErrorStream(final BufferedReader reader, final CmdCallback callback){
		new Thread(){
			public void run(){
				String buffer = null;
				try {
					while((buffer = reader.readLine()) != null){
						System.err.println(buffer);
						if(callback != null) callback.callBack(buffer);
					}
				} catch (IOException e) {
					e.printStackTrace();
				} catch(Exception e){
					e.printStackTrace();
				}
			}
		}.start();
	}
}
